// const input = "1234 567890 \t  7777   77";

const input = "123 456 789 0";

function* lexer(str) {
  let cursor = 0;
  let char = str[cursor];

  const next = () => {
    cursor++;
    char = str[cursor];
  };

  const number = () => {
    let buffer = "";

    while (
      char === "0" ||
      char === "1" ||
      char === "2" ||
      char === "3" ||
      char === "4" ||
      char === "5" ||
      char === "6" ||
      char === "7" ||
      char === "8" ||
      char === "9"
    ) {
      // TODO 符合的语法组合起来
      buffer += char;

      next();
    }

    if (buffer.length >= 1) {
      return {
        type: "number",
        value: Number(buffer),
      };
    }

    return null;
  };

  const whitespace = () => {
    let buffer = "";

    while (char === " " || char === "\t") {
      // TODO 符合的语法组合起来
      buffer += char;

      next();
    }

    if (buffer.length >= 1) {
      return {
        type: "whitespace",
        value: buffer,
      };
    }

    return null;
  };

  const eof = () => {
    // char = str[cursor];
    if (char === undefined) {
      return {
        type: "EOF",
      };
    }
    return null;
  };

  for (;;) {
    whitespace();
    const token = number() || eof();

    if (token) {
      if (token.type === "whitespace") {
        // 具有空格项的 token 跳过
        continue;
      }
      yield token;
      if (token.type === "EOF") {
        break;
      }
    } else {
      // 找到不符合的语法
      throw new SyntaxError(`Unexpected character "${char}" at ${cursor + 1}`);
    }
  }
}

console.log("start");
for (const token of lexer(input)) {
  console.log(token);
}
console.log("finish");

// console.log("start");
// console.log(JSON.stringify([...lexer(input)]));
// console.log("finish");
